#ifndef __KEY_DOWN__
#define __KEY_DOWN__
#include <iostream>
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include "cursor.h"
#include <map>
#include "player.h"
using namespace std;
class KeyDown{
	public:
		~KeyDown(){
			struct termios attr;
			tcgetattr(0,&attr);
			attr.c_lflag |=(ICANON|ECHO);
			tcsetattr(0,TCSANOW,&attr);
		}
		KeyDown(){
			struct termios attr;
			tcgetattr(0,&attr);
			attr.c_lflag &=~(ICANON|ECHO);
			tcsetattr(0,TCSANOW,&attr);
			keyMap.insert(pair<char,function<void(void)>>('A',bind(&Cursor::move,&cursor,Cursor::LEFT)));
			keyMap.insert(pair<char,function<void(void)>>('a',bind(&Cursor::move,&cursor,Cursor::LEFT)));
			
			keyMap.insert(pair<char,function<void(void)>>('w',bind(&Cursor::move,&cursor,Cursor::UP)));
			keyMap.insert(pair<char,function<void(void)>>('W',bind(&Cursor::move,&cursor,Cursor::UP)));
			
			keyMap.insert(pair<char,function<void(void)>>('d',bind(&Cursor::move,&cursor,Cursor::RIGHT)));
			keyMap.insert(pair<char,function<void(void)>>('D',bind(&Cursor::move,&cursor,Cursor::RIGHT)));
			
			keyMap.insert(pair<char,function<void(void)>>('s',bind(&Cursor::move,&cursor,Cursor::DOWN)));
			keyMap.insert(pair<char,function<void(void)>>('S',bind(&Cursor::move,&cursor,Cursor::DOWN)));
		}
		int click(Player *player){
			int ret=0;
			do{
				char c=getchar();
				if(c==' '){
					ret=player->checkPlay(cursor.getX(),cursor.getY());
					if(ret==1){
						break;
					}
				}else{
					auto it=keyMap.find(c);
					if(it!=keyMap.end()){
						auto func=it->second;
						func();
					}
				}
			}while(1);
			return ret;
		}
	private:
		Cursor cursor;
		map<char,function<void(void)>> keyMap;
};
#endif
